package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import com.sky.vo.UserReportVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * UserService
 *
 * @author liudo
 * @version 1.0
 * @project sky-take-out
 * @date 2024/2/22 10:25:58
 */
@Service
public class UserServiceImpl implements UserService {

    private static final String AUTHORIZATION_CODE = "authorization_code";
    private static final String URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public UserLoginVO login(String code) {
        // 1. 验票
        HashMap<String, String> params = new HashMap<>();
        params.put("appid", weChatProperties.getAppid());
        params.put("secret", weChatProperties.getSecret());
        params.put("js_code", code);
        params.put("grant_type", AUTHORIZATION_CODE);
        String responseJson = HttpClientUtil.doGet(URL, params);
        JSONObject jsonObject = JSON.parseObject(responseJson);
        // 查询刘姥姥是否存在
        String openid = jsonObject.getString("openid");
        User userQuery = new User();
        userQuery.setOpenid(openid);
        User user = userMapper.selectOne(userQuery);
        if (Objects.isNull(user)) {
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }
        // 返回token -- 为了后续访问资源 知道是谁
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(openid)
                .token(token)
                .build();
        return userLoginVO;
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> localDates = new ArrayList<>();
        if (begin.isEqual(end)) {
            localDates.add(begin);
        } else {
            localDates.add(begin);
            LocalDate nextDate = begin.plusDays(1);
            localDates.add(nextDate);
            while (!nextDate.isEqual(end)) {
                nextDate = nextDate.plusDays(1);
                localDates.add(nextDate);
            }
        }
        List<Map<String, Object>> result = userMapper.selectUserStatistics(localDates);

        String dateList = result.stream()
                .map(item -> (String) item.get("time"))
                .collect(Collectors.joining(","));

        String newUserList = result.stream()
                .map(item -> (Long) item.get("new_count"))
                .map(Object::toString)
                .collect(Collectors.joining(","));

        String totalUserList = result.stream()
                .map(item -> (Long) item.get("amount_count"))
                .map(Object::toString)
                .collect(Collectors.joining(","));

        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(dateList);
        userReportVO.setTotalUserList(totalUserList);
        userReportVO.setNewUserList(newUserList);

        return userReportVO;
    }
}
